/*
 * MVCME framework (www.radoslaw.biz/mvcme)
 * This framework is an attempt of creating MVC pattern for Java ME.
 * Feel free to change and distribute code and binaries of this project.
 * Should you want to provide any feedback, contact me at kowalski@radoslaw.biz
 */


package biz.radoslaw.mvcme.view;

import biz.radoslaw.mvcme.MIDletController;
import biz.radoslaw.mvcme.handler.EventHandlerFactory;
import java.util.Hashtable;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;

public abstract class View {
    
    protected MIDletController midlet;
    private Displayable displayable;
    private CommandListener commandListener;
    private Hashtable params = new Hashtable();

    public Hashtable getParams() {
        return params;
    }

    public void setParams(Hashtable params) {
        this.params = params;
    }

    public abstract Displayable generate();

    protected View() {
    }

    public Displayable getDisplayable() {
        try {
            if (displayable == null) {
                this.displayable = generate();
                if (this.commandListener==null)
                    setCommandListenerClass(midlet);
                this.displayable.setCommandListener(this.commandListener);
            }
            return displayable;
        } catch (Exception ex) {
            ex.printStackTrace();
            midlet.destroyApp(true);
            midlet.notifyDestroyed();
        }
        return null;
    }

    public void refresh() {}

    protected CommandListener getCommandListener() {
        return this.commandListener;
    }

    protected void setCommandListenerClass(Class commandListenerClass) {
        try {
            if (commandListenerClass != null) {
                this.commandListener = EventHandlerFactory.create(commandListenerClass);
            } else {
                this.commandListener = midlet;
            }
         } catch (Exception ex) {
            ex.printStackTrace();
            midlet.destroyApp(true);
            midlet.notifyDestroyed();
        }
    }

    protected void setCommandListenerClass(CommandListener commandListener) {
        this.commandListener = commandListener;
    }
}
